package com.houserent.service;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.houserent.dao.AcctDao;
import com.houserent.dao.HouseDao;
import com.houserent.dao.LogDao;
import com.houserent.dao.MsgDao;
import com.houserent.dao.OrderDao;
import com.houserent.entry.AcctInfo;
import com.houserent.entry.HouseInfo;
import com.houserent.entry.HouseResult;
import com.houserent.entry.LogInfo;
import com.houserent.entry.MsgInfo;
import com.houserent.entry.OrderInfo;
import com.houserent.utils.HouseUtils;

@Service
@Transactional
public class OrderServiceimpl implements OrderService {

    @Resource
    private HouseDao houseDao;
    @Resource
    private LogDao logDao;
    @Resource
    private OrderDao orderDao;
    @Resource
    private AcctDao acctDao;
    @Resource
    private MsgDao msgDao;

    // 新用户入住
    @Override
    public HouseResult addCust(String houseId, String userName, String userCertNum, String userLinkPhone,
            String userSex, String userEmail, String userqq, String useStartDate, String useType, String payGuarantyFee) {
        if (HouseUtils.isEmpty(houseId, userName, userCertNum, userLinkPhone, userSex, userEmail, userqq, useStartDate,
                useType, payGuarantyFee)) {
            return new HouseResult(HouseResult.ERROR_CODE, "录入的信息均不允许为空,请检查", "");
        }
        // 获取到房间的信息
        HouseInfo house = houseDao.getHouseInfoByHouseId(houseId);
        if (HouseUtils.isEmpty(house)) {
            return new HouseResult(HouseResult.ERROR_CODE, "未获取到要入住的房间信息,请重试", "");
        }
        // double houseRent = house.getHouse_rent();
        // 1.生成用户的临时账号
        String houseNumber = house.getHouse_number();
        String userType = "01";// 租客
        String isFull = "01";// 完整信息
        String userId = HouseUtils.createUserID(logDao, houseNumber);
        String password = HouseUtils.createUserPassWord();
        LogInfo user = new LogInfo(userId, password, userType, userLinkPhone, userSex, userName, userCertNum,
                userEmail, userqq, isFull, null, null);
        logDao.register(user);

        // 2.生成订单
        String orderId = HouseUtils.createOrderID();
        // 根据租用类型计算理论结束日期
        useStartDate = HouseUtils.TransDate(useStartDate, "yyyy-MM-dd", "yyyyMMddHHmmss");
        String expectEndDate = "";
        if ("00".equals(useType)) {// 月租,结束时间下月
            expectEndDate = HouseUtils.rollDateStr(useStartDate, "yyyyMMddHHmmss", Calendar.MONTH, 1);
        }
        else if ("01".equals(useType)) {// 季租,结束时间三个月后今天
            expectEndDate = HouseUtils.rollDateStr(useStartDate, "yyyyMMddHHmmss", Calendar.MONTH, 3);
        }
        else if ("02".equals(useType)) {// 半年租,结束时间半年后今天
            expectEndDate = HouseUtils.rollDateStr(useStartDate, "yyyyMMddHHmmss", Calendar.MONTH, 6);
        }
        else if ("03".equals(useType)) {// 年租,结束时间明年今日
            expectEndDate = HouseUtils.rollDateStr(useStartDate, "yyyyMMddHHmmss", Calendar.YEAR, 1);
        }
        int orderStatus = 1;// 预定
        if (HouseUtils.isBig(HouseUtils.getSysDate(), useStartDate)) {
            orderStatus = 2;// 租用中
        }
        // 最后一次缴费的时间,默认用户入住的时间
        String lastFeeTime = useStartDate;
        // 房主信息
        LogInfo host = logDao.login(house.getHost_id());
        String hostName = host.getReal_name();
        String para1 = payGuarantyFee;// para1字段放入用户缴纳的押金
        OrderInfo order = new OrderInfo(orderId, userId, host.getUser_id(), houseId, userName, hostName, userLinkPhone,
                userCertNum, useStartDate, expectEndDate, userType, orderStatus, lastFeeTime, "", "", para1, null);
        order.setOrder_start_date(HouseUtils.getSysDate());// 订单的开始时间为当前时间
        orderDao.addCust(order);

        // 3.修改房间状态以及录入使用人和押金
        HouseInfo updateHouse = new HouseInfo();
        updateHouse.setHouse_id(house.getHouse_id());
        updateHouse.setCan_use_tag("0");// 设置房间不可用
        updateHouse.setHouse_user_id(userId);// 设置房间的使用人
        houseDao.useHouse(updateHouse);
        // 4.生成下月账单
        String acctId = HouseUtils.createAcctID();
        String acctType = useType;// 费用类型
        String acctStartDate = useStartDate;// 账单起始日期为用户开始入住的时间
        String acctEndDate = HouseUtils.rollDateStr(acctStartDate, "yyyyMMddHHmmss", Calendar.MONTH, 1);// 账单结束日期
        String payTag = "0";// 未付费
        String ortherChange = "网费:50元,物业费:100元";
        // 总费用
        double totleFee = house.getHouse_rent() + house.getWater_charge() + house.getPower_charge();
        AcctInfo acct = new AcctInfo(acctId, orderId, acctType, house.getHouse_rent(), house.getPower_charge(),
                house.getWater_charge(), 0, ortherChange, acctStartDate, acctEndDate, payTag, totleFee, null, null);
        acctDao.createAcct(acct);
        return new HouseResult(HouseResult.SUCCESS_CODE, "登记完成,请牢记系统账号密码[账号:" + userId + ",密码:" + password + "]", "");
    }

    @Override
    public HouseResult endOrder(String houseId) {
        List<OrderInfo> orders = orderDao.getOdrerInfo(houseId);
        if (HouseUtils.isEmpty(orders)) {
            return new HouseResult(HouseResult.ERROR_CODE, "未获取到房间信息,请重试", "");
        }
        if (orders.size() > 1) {
            return new HouseResult(HouseResult.ERROR_CODE, "获取到的订单信息出错,请重试!", "");
        }
        OrderInfo order = orders.get(0);
        if (HouseUtils.isBig(HouseUtils.getSysDate(), order.getLast_fee_time())) {
            return new HouseResult(HouseResult.ERROR_CODE, "有未完账单,请先结算", "");
        }
        // 1.删除下月的账单
        Map dataMap = HouseUtils.asMap("houseId", order.getHouse_id(), "userId", order.getUser_id());
        List<AcctInfo> accts = acctDao.getAcctInfoByHouseUser(dataMap);
        for (AcctInfo acct : accts) {
            // 获取到未付费并且结束时间比最后一次交费时间晚的账单
            String acctEndDate = HouseUtils.TransDate(acct.getEnd_date(), "yyyy-MM-dd", "yyyyMMddHHmmss");
            if ("0".equals(acct.getPay_tag()) && HouseUtils.isBig(acctEndDate, order.getLast_fee_time())) {
                acctDao.deleteAcct(acct.getAcct_id());
            }
        }
        // 2.修改订单状态
        double guarantyFee = Double.valueOf(order.getPara1());
        dataMap = HouseUtils.asMap("status", 3, "orderId", order.getOrder_id(), "endDate", HouseUtils.getSysDate());
        orderDao.modifyOrderStatus(dataMap);
        // 3.修改房间状态,并退还押金
        houseDao.unUseHouse(houseId);
        // 4.删除用户发送过的消息
        String userId = order.getUser_id();
        msgDao.deleteMsg(userId);
        // 5.删除用户临时账号
        logDao.deleteTempUser(userId);
        return new HouseResult(HouseResult.SUCCESS_CODE, "退订成功!欢迎下次入住,需退还押金:" + guarantyFee + "元", "");
    }

    @Override
    public HouseResult optOrder(String orderId, String optType) {
        // 操作订单
        OrderInfo order = orderDao.selOdrerInfoByOrderId(orderId);
        if ("退房".equals(optType)) {
            return endOrder(order.getHouse_id());
        }
        if ("收租".equals(optType)) {
            MsgInfo msg = new MsgInfo();
            msg.setMsg_id(HouseUtils.createMsgID());
            LogInfo host = logDao.login(order.getHost_id());
            msg.setAuthor_id(order.getHost_id());
            msg.setAuthor_name(host.getReal_name());
            msg.setUser_type(host.getUser_type());
            msg.setRecive_id(order.getUser_id());
            msg.setMsg_type("0");// 消息
            msg.setRead_tag("0");// 未读
            msg.setMsg_content("<p>亲爱的住户您好,请缴纳本月房租</p>");
            msg.setSend_date(HouseUtils.getSysDate());
            msgDao.sendMsg(msg);
            return new HouseResult(HouseResult.SUCCESS_CODE, "已提醒住户缴纳房租", "");
        }
        if ("删除".equals(optType)) {
            orderDao.deleteOrder(orderId);
            return new HouseResult(HouseResult.SUCCESS_CODE, "订单删除成功!", "");
        }
        return new HouseResult(HouseResult.SUCCESS_CODE, "操作成功!", "");
    }
}
